﻿using System;
using SimpleServiceBus.Bus.MessageManagement.MessageHandling;
using SimpleServiceBus.Bus.Pipeline;
using SimpleServiceBus.Messages.Management.Monitoring;
using SimpleServiceBus.Persistence.Domain.Management.Entities;
using SimpleServiceBus.Persistence.Domain.Management.Repositories;
using SimpleServiceBus.Utilities;
using SimpleServiceBus.Utilities.Email;

namespace SimpleServiceBus.Endpoint.Management.Monitoring.Server.MessageHandlers
{
    public class EndpointErrorMessageHandler : IMessageHandler<EndpointErrorNotification>
    {
        private const string ErrorSubjectTemplate = @"Endpoint Exception for {0}, {1}";
        private const string ErrorEmailTemplate =
            @"An exception occurred on endpoint {0} at {1} while processing a message with a MessageID of {2}. {4} Exception: {4}{4} {3}";
        
        public void Handle(EndpointErrorNotification message, IMessageContext context)
        {
            string emailAddress = null;

            var endpointRepository = context.GetLocalService<IEndpointRepository>();
            var emailer = context.GetLocalService<IEmailService>();

            if (emailer == null)
                return;

            if (endpointRepository != null)
            {
                ManagedEndpoint endpoint = endpointRepository.GetByEndpointId(message.EndpointID);
                if (endpoint != null && !String.IsNullOrEmpty(endpoint.SupportEmailAddress))
                    emailAddress = endpoint.SupportEmailAddress;

            }

            if (emailAddress == null)
                emailAddress = context.EndpointMetadata.SupportEmailAddress;

            if (emailAddress.IsNonEmpty())
            {
                string subject = String.Format(ErrorSubjectTemplate, message.EndpointID, message.ErrorMessage.Elide(30));
                string body = String.Format(ErrorEmailTemplate, message.EndpointID, message.StatusTime,
                                            message.FailedMessageID, message.ErrorMessage, Environment.NewLine);
                emailer.Send(subject,body, emailAddress);
            }
        }
       
    }
}
